#!/usr/bin/env python
#-*- coding:utf-8 -*-

from PyQt4 import QtGui, QtCore
import threading, subprocess, time, os

def source2text(source):
  text = '<body bgcolor="white" text="black">'
  s = source.replace("\n", "<br>")
  while True:
    if s == '':
      break
    i = s.find("<@")
    if i == -1:
      text += s
      s = ''
    else:
      text += s[:i]
      i = s.find("@>")
      if i != -1:
        s = s[i+2:]
  text += "</body>"
  return text

def source2data(source):
  data = []
  s = source
  e = ''
  st = [False]*3
  for c in s:
    e += c
    if not any(st) and c == '<':
      st[0] = True
    elif st == [True, False, False] and c == '@':
      st[1] = True
      data.append(['s',e[:-2]])
      e = ''
    elif st == [True, False, False] and c != '@':
      st[0] = False
    elif st == [True, True, False] and c == '@':
      st[2] = True
    elif all(st) and c == '>':
      st = [False]*3
      st[0] = False
      st[1] = False
      st[2] = False
      data.append(['c',e[:-2]])
      e = ''
    elif all(st) and c != '>':
      st[2] = False
  data.append(['s',e])
  return data

class Preprocessor(QtCore.QThread):
  def __init__(self):
    QtCore.QThread.__init__(self)
    self.start_flag = False
    self.run_flag = True
    self.data_list = []
    self.deflang = "hu"
    self.lang = "hu"
    self.prevlang = ""
    self.speed = 170
    self.rep = -1
    self.rpos = -1
  def set_source(self, source):
    self.source = source
    self.text = source2text(self.source)
    self.data_list = source2data(self.source)
  def get_text(self):
    return self.text
  def start_espeak(self):
    self.start_flag = True
  def stop_espeak(self):
    self.start_flag = False
    try:
      self.proc1.kill()
      self.proc2.kill()
    except:
      pass
  def set_speed(self, speed):
    self.speed = speed
  def save_soundfile(self, filename):
    if len(filename) > 0:
      o = open(filename+".txt", "w")
      o.write(self.text.encode("utf-8"))
      o.close()
      os.system(u'espeak -m -v '+self.deflang+'-s '+str(self.speed)+' --stdout -f ' + filename + u'.txt >' + filename)
  def exit_prep(self):
    self.stop_espeak()
    self.run_flag = False
  def proc(self, data):
    if data[0] == 's':
      self.proc1 = subprocess.Popen(['espeak', '-m', '-s', str(self.speed), '--stdout', '-v', self.lang, data[1]], stdout=subprocess.PIPE)
      self.proc2 = subprocess.Popen(['paplay'], stdin=self.proc1.stdout)
      self.proc2.communicate()
    else:
      c = data[1].split("=")
      if c[0] == "wait":
        time.sleep(int(c[1]))
      elif c[0] == "lang":
        self.prevlang = self.lang
        self.lang = c[1]
      elif c[0] == "/lang":
        self.lang = self.prevlang
      elif c[0] == "rep":
        self.rep = int(c[1])
        self.rpos = self.pos
      elif c[0] == "/rep":
        self.rep -= 1
        if self.rep > 0:
          self.pos = self.rpos
  def run(self):
    self.pos = 0
    while self.run_flag:
      if self.start_flag:
        self.proc(self.data_list[self.pos])
        self.pos += 1
        if self.pos == len(self.data_list):
          self.pos = 0
      else:
        time.sleep(1)
        self.pos = 0
